﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Linq;

namespace System.Windows.Controls
{
    public static class ItemsControlExtention
    {
        /// <summary>
        /// Enumerates all the items that are currently visible in am ItemsControl. This implementation assumes
        /// that a VirtualizingStackPanel is being used as the ItemsPanel.
        /// </summary>
        public static IEnumerable<FrameworkElement> GetItemsInView(this ItemsControl itemsControl)
        {
            // locate the stack panel that hosts the items
            VirtualizingStackPanel vsp = itemsControl.GetItemsHost();
            // iterate over each of the items in view
            int firstVisibleItem = (int)vsp.VerticalOffset;
            int visibleItemCount = (int)vsp.ViewportHeight;
            for (int index = firstVisibleItem; index <= firstVisibleItem + visibleItemCount + 1; index++)
            {
                var item = itemsControl.ItemContainerGenerator.ContainerFromIndex(index) as FrameworkElement;
                if (item == null)
                    continue;
                yield return item;
            }
        }


        public static VirtualizingStackPanel GetItemsHost(this ItemsControl itemsControl)
        {
            VirtualizingStackPanel _itemsHost = null;
            if (itemsControl != null && itemsControl.ItemContainerGenerator != null)
            {
                DependencyObject container = itemsControl.ItemContainerGenerator.ContainerFromIndex(0);
                if (container != null)
                {
                    _itemsHost = VisualTreeHelper.GetParent(container) as VirtualizingStackPanel;
                }
                else
                {
                    _itemsHost = itemsControl.GetVisualDescendants().OfType<VirtualizingStackPanel>().FirstOrDefault();
                }
            }
            return _itemsHost;
        }


        public static ScrollViewer GetScrollHost(this ItemsControl itemsControl)
        {
            ScrollViewer _scrollHost = null;
            Panel itemsHost = itemsControl.GetItemsHost();
            if (itemsHost != null)
            {
                for (DependencyObject obj = itemsHost; obj != itemsControl && obj != null; obj = VisualTreeHelper.GetParent(obj))
                {
                    ScrollViewer viewer = obj as ScrollViewer;
                    if (viewer != null)
                    {
                        _scrollHost = viewer;
                        break;
                    }
                }
            }
            return _scrollHost;
        }
    }
}
